package com.test.springboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Druid数据源的其它参数配置;
 * 如果在一个项目的数据源中配置了druid的后台管理servlet以及监控filter。就可以在项目的druid请求中查看到jdbc的监控数据;
 * 例：localhost:8080/druid，使用可以使用配置的登录账号用密码来登录了。从而查看jdbc的监控数据；
 *
 * @create: 2019-06-24 13:44
 **/
@Configuration
public class DruidConfig {

    //将yml文件中的属性注入到druidDataSource中，并注入到spring容器中
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid() {
        return new DruidDataSource();
    }


    //配置druid的监控
    //1.配置一个后台管理的servlet
    @Bean
    public ServletRegistrationBean statViewFilter() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        Map<String, String> initParameters = new HashMap<>();
        //账号密码
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "123456");
        //访问设置
        initParameters.put("allow", ""); //默认允许所有
        initParameters.put("deny", "192.168.45.129"); //拒绝访问

        bean.setInitParameters(initParameters);
        return bean;
    }

    //2.配置一个监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("exclusions", "*.js,*.css,/druid/*");

        bean.setInitParameters(initParameters);

        //拦截所有请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

}
